# -*- coding:utf-8 -*-


from flask import Flask,jsonify,abort,make_response,url_for,request
from flask_restful import Api,Resource
from flask_httpauth import HTTPBasicAuth
import platform,subprocess,time,threading
import redis

app = Flask(__name__)
api = Api(app)
auth = HTTPBasicAuth()


tasks = [
    {
        'id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
        'done': False
    },
    {
        'id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web',
        'done': False
    }
]

users = [
    {'username': 'admin', 'password': 'admin'},
]


pool = redis.ConnectionPool(host='10.68.60.112', port=26379,db=0,socket_connect_timeout=30,password='admin',encoding='utf-8',decode_responses=True)
r = redis.Redis(connection_pool=pool)




def make_public_task(task):
    new_task = {}
    for field in task:
        if field == 'id':
            new_task['id']=task['id']
#            new_task['uri'] = url_for('get_task', task_id=task['id'], _external=True)           
        else:
            new_task[field] = task[field]
    return new_task



@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Api Message Not found'}), 404)

@auth.get_password
def get_password(username):
    for user in users:
        if user['username'] == username:
            return user['password']
    return None

@auth.error_handler
def unauthorized():
    return make_response(jsonify({'error': 'Unauthorized access'}), 401)

@app.route('/')
def hello_world():
    return 'Hello Flask!'




class TaskListAPI(Resource):
    def get(self):
        return jsonify({'tasks': list(map(make_public_task, tasks))})

    @auth.login_required
    def post(self):
        if not request.json or not 'title' in request.json:
            abort(400)
        task = {
        'id': tasks[-1]['id'] + 1,
        'title': request.json['title'],
        'description': request.json.get('description', ""),
        'done': False
    }
        tasks.append(task)
        return jsonify({'task': task}), 201

class TaskAPI(Resource):
    
    def get(self,task_id):
        task = filter(lambda thelist: thelist['id'] == task_id, tasks)
        t=list(task)
        if len(t) == 0:
            abort(404)
        return jsonify({'task': t})
    
    @auth.login_required
    def put(self,task_id):
        task = filter(lambda t: t['id'] == task_id, tasks)
        task=list(task)
        if len(task) == 0:
            abort(404)
        if not request.json:
            abort(400)
        if 'title' not in request.json:
            abort(400)
        if 'done' in request.json and type(request.json['done']) is not bool:
            abort(400)
        task[0]['title'] = request.json.get('title', task[0]['title'])
        task[0]['description'] = request.json.get('description', task[0]['description'])
        task[0]['done'] = request.json.get('done', task[0]['done'])
        return jsonify({'task': task[0]})

    @auth.login_required
    def delete(self,task_id):
        task = filter(lambda t: t['id'] == task_id, tasks)
        t=list(task)
        if len(t) == 0:
            abort(404)
        tasks.remove(t[0])
        return jsonify({'result': True})
    

api.add_resource(TaskListAPI, '/todo/api/v1.0/tasks', endpoint = 'tasks')
api.add_resource(TaskAPI, '/todo/api/v1.0/tasks/<int:id>', endpoint = 'task')

if __name__ == '__main__':
    app.run(host='0.0.0.0',debug=True)